package com.lagou.rpc.consumer.client;

import com.lagou.rpc.consumer.handler.RpcClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 客户端
 * 1。连接Netty服务
 * 2。提供给调用者主动关闭资源的方法
 * 3。给提供者提供发送消息的方法（调用者可以通过这个方法将消息发送到Netty服务端）
 */
public class RpcClient {

    private RpcClientHandler rpcClientHandler = new RpcClientHandler();
    //创建线程池用于发送消息
    private ExecutorService executorService = Executors.newCachedThreadPool();

    private EventLoopGroup eventLoopGroup;
    private Channel channel;

    private String ip;
    private int port;

    public RpcClient(String ip, int port) {
        this.ip = ip;
        this.port = port;
        initClient();
    }



    /**
     * 初始化方法-连接Netty客户端
     */
    public void initClient(){
        try {
            //1。创建线程组
            eventLoopGroup = new NioEventLoopGroup();
            //2。创建启动助手
            Bootstrap bootstrap = new Bootstrap();
            //3。设置参数
            bootstrap.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)   //设置通道活跃的状态
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000) //设置连接超时时间
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            //添加String类型的编解码器
                            pipeline.addLast(new StringEncoder());
                            pipeline.addLast(new StringDecoder());
                            // 添加客户端处理类
                            pipeline.addLast(rpcClientHandler);

                        }
                    });
            //4。连接Netty客户端
            channel = bootstrap.connect(ip, port).sync().channel();
        } catch (Exception e){
            e.printStackTrace();
            if (channel != null){
                channel.close();
            }
            if (eventLoopGroup != null){
                eventLoopGroup.shutdownGracefully();
            }
        }
    }

    /**
     * 提供给调用者主动关闭资源的方法
     */
    public void close(){
        if (channel != null){
            channel.close();
        }
        if (eventLoopGroup != null){
            eventLoopGroup.shutdownGracefully();
        }
    }

    /**
     * 给提供者提供发送消息的方法
     */
    public Object send(String msg) throws ExecutionException, InterruptedException {
        rpcClientHandler.setRequestMsg(msg);
        Future submit = executorService.submit(rpcClientHandler);
        return submit.get();
    }

}
